package org.ftz.JudgeOnline.Java;
import org.ftz.control.util;
import java.io.FileWriter;
import java.io.IOException;
public class ExecuteJava {
    public static String runJava(String code,String input){
        String output; //输出
        util.writeFile(input); //将输入数据写入到文件
        String[] split = code.split("\\{");
        String[] split1 = split[0].split(" "); //获取输入代码的类名
        String name=split1[split1.length-1];
        String DIR="D:\\BigProgram\\";
        String DIR1="D:\\BigProgram";
        String javaFile=DIR+name+".java";
        String javaClass=name;
        String compileCmd=String.format("javac -encoding utf8 %s -d %s",javaFile,DIR1);
        String runningCmd=String.format("cmd /c java -classpath %s %s < D:\\BigProgram\\1.txt", DIR1, javaClass);
        System.out.println(compileCmd+"\n"+runningCmd);
        FileWriter writer= null;  //将代码写入到定义路径下特定的java源文件中
        try {
            writer = new FileWriter(javaFile);
            writer.write(code);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Answer answer= ExecUtil.run(compileCmd,false,true); //编译源文件为class文件
        if(answer.getError()==0) { //若编译成功即可开始运行
            answer = ExecUtil.run(runningCmd, true, true);
            if(answer.getError()!=0){
                answer.setReason(Answer.Success);
            }else{
                answer.setReason(Answer.RuntimeError);
            }
            output="运行成功@"+answer.getStdout();
            System.out.println(output); //输出正确运行结果
        }else{
            answer.setReason(Answer.Error);
            output=answer.getReason()+answer.getStderr();
            System.out.println(output); //输出错误提示
        }
        return output;
    }
}
